<template>
    <n-form
        style="margin-top: 24px"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="top"
        label-width="120"
        require-mark-placement="right-hanging"
    >
        <n-form-item label="应用编号" path="sn">
            <n-input v-model:value="form.sn" placeholder="请输入应用编号" :on-input="handleInput"></n-input>
        </n-form-item>
        <n-form-item label="应用名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入应用名称"></n-input>
        </n-form-item>
        <n-form-item label="应用类型" path="appType">

            <jb-radio-group :disabled="props.id"
                v-model:value="form.appType"
                url="/aiApp/getAppType"
            ></jb-radio-group>
        </n-form-item>

        <n-form-item label="应用简介" path="">
            <n-input v-model:value="form.briefInfo" type="textarea" style="min-height: 200px" placeholder="请输入应用简介"></n-input>
        </n-form-item>
    </n-form>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {JBoltApi} from '@/service/request'

const props = defineProps({
    id: {
        type: String
    }
})


const formRef = ref(null)

const form = ref({
    id: '',
    sn: "",
    name: "",
    briefInfo: "",
    appType: "app_simple"
})

const rules = {
    name: {
        required: true,
        message: '请输入名称',
        trigger: 'change'
    },
    appType: {
        required: true,
        message: '请选择应用类型',
        trigger: 'change'
    },
    sn: {
        required: true,
        message: '请输入编码',
        trigger: 'change'
    }
}
// 处理输入事件的函数
const handleInput = (value) => {
    // 定义正则表达式，只允许英文字母和数字
    const regex = /^[a-zA-Z0-9]*$/;
    if (regex.test(value)) {
        // 如果输入符合规则，更新输入框的值
        form.value.sn = value;
    } else {
        // 如果输入不符合规则，截取符合规则的部分
        form.value.sn = value.replace(/[^a-zA-Z0-9]/g, '');
    }
};

async function submit(fun) {
    await formRef.value?.validate()

    console.debug('提交表单', form.value)

    let url = props.id ? '/aiApp/update' : '/aiApp/add'

    await JBoltApi.tryPost(url, form.value)


    if (fun) {
        fun()
    }

    return true
}

defineExpose({
    submit
})

async function loadEditData() {
    const {result} = await JBoltApi.get(`/aiApp/getById/${props.id}`)
    if (result) {
        form.value = result.data
    }

}

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})


</script>

<style scoped lang="scss">
.text_tip {
    font-size: 12px;
    color: #999;
}
</style>